#!/usr/bin/env python2
# coding=utf-8

from CheckXSS import CheckXSS
from dbconnetion import DB
from PyQt4 import QtCore
import json

class Scaner(QtCore.QThread):
    logemit = QtCore.pyqtSignal(str)
    labemit = QtCore.pyqtSignal(str)
    endimit = QtCore.pyqtSignal()

    def __init__(self):
        super(Scaner, self).__init__()
        self.db = DB()
        self.xss = []

    def run(self):
        self.logemit.emit(u"XSS检查开始")
        self.general_pattern()
        self.db.start()
        all_checkpoint = self.db.select('select id, url_full from get_url') #' where id = 34848')

        try:
            for checkpoint in all_checkpoint:
                print checkpoint[1]
                ch = CheckXSS(checkpoint[1], self.xss)
                self.storeResult(checkpoint[0], ch.result)
                del ch
        finally:
            self.db.close()

        self.logemit.emit(u"XSS检查结束")

    def general_pattern(self):
        self.db.start()
        xss = self.db.select('select * from xss_pattern')
        if xss:
            for row in xss:
                self.xss.append({'id': row[0], 'code':row[1], 'result':row[2]})
        self.db.close()

    def storeResult(self, uid, result):
        sql = "insert into xss_scan " \
              "(url_id, status, submit_method, patterns, result) values" \
              "(?, ?, ?, ?, ?)"

        cursor = self.db.select('select * from xss_scan where url_id=%d'%uid)
        row = cursor.fetchone()

        if result:
            method = 'GET'
            xss = []
            res1 = ''

            for res in result:
                # print sql
                if method == 'GET':
                    method = res['method']
                xss.append(res['xss'])
                if res1 != 'danger':
                    res1 = res['result']

            if row:
                self.db.insert('update xss_scan set submit_method=?, patterns=?, result=? where url_id=?',
                               (json.dumps(method), json.dumps(xss), res1, uid))
            else:
                self.db.insert(sql, (uid, 'checked', json.dumps(method), json.dumps(xss), res1))
        else:
            if not row:
                self.db.insert(sql, (uid, 'checked', None, None, 'unknown'))
            else:
                self.db.insert('update xss_scan set submit_method=?, patterns=?, result=? where url_id=?',
                               (None, None, 'unknown',uid))

    def terminate(self):
        self.db.close()
        super(Scaner, self).terminate()

if __name__== '__main__':

    Scaner().start()